package cn.mall.order.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.mall.base.constants.BaseConstants;
import cn.mall.base.exception.UserBaseException;
import cn.mall.base.utils.AjaxResult;
import cn.mall.base.utils.PageList;
import cn.mall.base.utils.VideoUtils;
import cn.mall.bill.domain.Bill;
import cn.mall.bill.mapper.BillMapper;
import cn.mall.goods.domain.Goods;
import cn.mall.goods.mapper.GoodsMapper;
import cn.mall.order.domain.Copy;
import cn.mall.order.domain.Order;
import cn.mall.order.domain.UserOrderStatusCounts;
import cn.mall.order.dto.*;
import cn.mall.order.mapper.OrderMapper;
import cn.mall.order.query.OrderQuery;
import cn.mall.order.service.IOrderService;
import cn.mall.base.service.impl.BaseServiceImpl;
import cn.mall.order.utils.ConmentUtils;
import cn.mall.order.utils.Utils;
import cn.mall.order.utils.WeiboDataAsync;
import cn.mall.order.utils.WeiboDataCacheUtils;
import cn.mall.org.domain.Shop;
import cn.mall.org.mapper.ShopMapper;
import cn.mall.user.domain.User;
import cn.mall.user.mapper.UserMapper;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author myf
 * @since 2023-12-07
 */
@Service
@Transactional
public class OrderServiceImpl extends BaseServiceImpl<Order> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private BillMapper billMapper;

    @Autowired
    private WeiboDataAsync weiboDataCollector;

    @Autowired
    private WeiboDataCacheUtils weiboDataCacheService;

    /**
     * 前端  传递
     * 商品id sId
     * 商家id ShopId
     * 用户id  uId
     * url
     * finalPrice
     * count
     *
     * @param order
     * @return
     */
    @Override
    @Transactional
    public Object addOrder(Order order) throws IOException, JSONException {
        //判断是否还存在这个订单
        Goods goods = goodsMapper.loadById(order.getSId());
        if(ObjectUtil.isEmpty(goods)){
            throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("下单失败！ " +"商品已下架请刷新页面"));
        }

        //拿到uid  判断余额是否足够
        User user = userMapper.loadById(order.getUId());

        Integer count = order.getCount();
        BigDecimal price = goods.getPrice();
        BigDecimal bigcount = new BigDecimal(count);
        order.setFinalPrice(bigcount.multiply(price));
        if (ObjectUtils.isEmpty(user.getBalance()) || (user.getBalance().subtract(order.getFinalPrice()).compareTo(BigDecimal.ZERO) < 0)) {
            throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("余额不足,当前余额:" + (user.getBalance() == null ? "0" : user.getBalance().toString()) + "  请充值"));
        }

        Shop shop = shopMapper.loadById(order.getShopId());
        // 设置商家 id
        order.setShopId(shop.getBusinessId());

        //设置订单状态为 待处理
        order.setOType(BaseConstants.Order.STATE_PENDORDER);

        order.setGoods(goods);
        
        // 处理URL
        String url = null;
        if(order.getUrl() != null) {
            url = order.getUrl().trim();
            order.setUrl(newToUrl(url));
        }

        // URL验证 (对于非类型10的商品)
        if(order.getGoods().getType() != 10) {
            if(order.getUrl() == null || order.getUrl().isEmpty()) {
                throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("链接有误，请检查链接"));
            }
        }

        // 设置订单默认初始值，后续异步更新
        setDefaultInitialValues(order);

        // 设置订单号
        String oid = UUID.randomUUID().toString();
        order.setOId(oid);

        // 设置订单剩余量
        order.setSurplus(order.getCount());

        // 设置创建时间
        order.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));

        // 设置完成度
        order.setCompletion(0);

        // 扣减余额
        BigDecimal result = user.getBalance().subtract(order.getFinalPrice());
        user.setBalance(result);
        userMapper.update(user);

        // 保存订单
        orderMapper.insert(order);

        // 插入账单
        Bill bill = new Bill();
        bill.setMoney(order.getFinalPrice());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(new Date());
        bill.setTime(formattedDate);
        bill.setUserid(order.getUId());
        User user1 = userMapper.loadById(user.getId());
        bill.setBalance(user1.getBalance());
        bill.setOid(order.getOId());
        bill.setUrl(order.getUrl());
        bill.setBtype(2);
        Bill bill1 = setBillType(bill, goods);
        billMapper.insert(bill1);

        return oid;
    }

    /**
     * 设置默认的初始数据值
     * 设置为null而不是0，以便管理员知道数据正在爬取中
     */
    private void setDefaultInitialValues(Order order) {
        // 设置为null而不是0，表示数据正在爬取中
        order.setSForward(null);
        order.setSComment(null);
        order.setSGood(null);
        order.setSFollow(null);
        order.setSVideo(null);
        
        if(order.getGoods().getType() == 7) {
            // 真人转评赞商品类型的特殊处理
            order.setCompletionSf(0);
            order.setCompletionSc(0);
            order.setCompletionSg(0);
            order.setSurplusSf(order.getCount());
            order.setSurplusSc(order.getCount());
            order.setSurplusSg(order.getCount());
        }
    }

    /**
     * 判断订单是否需要初始数据
     */
    private boolean needInitialDataForOrder(Order order) {
        Integer type = order.getGoods().getType();
        return type != 5; // 类型5的商品不需要抓取初始数据
    }

    /**
     * 尝试从缓存加载数据，如果成功返回true
     */
    private boolean tryLoadDataFromCache(Order order) {
        if (order.getGoods().getType() == 1) {
            // 关注类型
            Integer cachedData = weiboDataCacheService.getCachedFollowData(order.getUrl());
            if (cachedData != null) {
                order.setSFollow(cachedData);
                return true;
            }
        } else if (order.getGoods().getType() == 6) {
            // 视频类型
            Integer cachedData = weiboDataCacheService.getCachedVideoData(order.getUrl());
            if (cachedData != null) {
                order.setSVideo(cachedData);
                return true;
            }
        } else if (order.getGoods().getType() == 10) {
            // 内评赞类型
            Integer cachedData = weiboDataCacheService.getCachedCommentGoodData(order.getRefundNumber());
            if (cachedData != null) {
                order.setSGood(cachedData);
                return true;
            }
        } else if (order.getGoods().getType() != 5) {
            // 其他类型商品
            ArrayList<Integer> cachedData = weiboDataCacheService.getCachedBaseData(order.getUrl());
            if (cachedData != null && cachedData.size() == 3) {
                order.setSForward(cachedData.get(0));
                order.setSComment(cachedData.get(1));
                order.setSGood(cachedData.get(2));
                return true;
            }
        }
        return false;
    }

    /**
     * 同步获取初始数据(只在缓存未命中时执行)
     */
    private void fetchInitialDataSync(Order order) throws IOException, JSONException {
        try {
            if (order.getGoods().getType() == 1) {
                // 关注类型
                String fllow = Utils.getFllow();
                String subValue = Utils.getSubValue(fllow);
                FllowDto fllowDto = new FllowDto();
                fllowDto.setSub(subValue);
                fllowDto.setUrl(order.getUrl());
                Integer followdata = Utils.getFollowdata(fllowDto);
                order.setSFollow(followdata);
            } else if (order.getGoods().getType() == 6) {
                // 视频类型
                // 视频数据的采集是必要的，但数据采集过程可能较慢
                // 这里仍然同步获取初始值，但设置更短的超时
                AjaxResult ajaxResult = VideoUtils.ToolUtils(order.getUrl());
                if (ajaxResult.getSuccess()) {
                    String videoData = (String) ajaxResult.getResultObj();
                    if (videoData != null) {
                        Integer sv = VideoUtils.convertToWan(videoData);
                        order.setSVideo(sv);
                    }
                }
            } else if (order.getGoods().getType() == 10) {
                // 内评赞
                String taskid = order.getRefundNumber();
                if (ConmentUtils.GetComment(taskid).getSuccess()) {
                    String s1 = (String) ConmentUtils.GetComment(taskid).getResultObj();
                    if (s1 != null) {
                        Integer sg = VideoUtils.convertToWan(s1);
                        order.setSGood(sg);
                    }
                }
            } else if (order.getGoods().getType() != 5) {
                // 其他类型
                String url = order.getUrl();
                if (!url.contains("m.weibo.cn")) {
                    url = Utils.dealStr(url);
                }
                try {
                    AjaxResult result = Utils.ToolUtils(url);
                    if (result.getSuccess() && result.getResultObj() != null) {
                        ArrayList<Integer> arrayList = (ArrayList<Integer>) result.getResultObj();
                        order.setSForward(arrayList.get(0));
                        order.setSComment(arrayList.get(1));
                        order.setSGood(arrayList.get(2));
                    }
                } catch (Exception e) {
                    // 如果获取失败，使用默认值并继续处理
                }
            }
        } catch (Exception e) {
            // 数据采集失败不影响下单流程，使用默认值
        }

        // 在fetchInitialDataSync方法末尾添加缓存数据代码
        if (order.getGoods().getType() == 1) {
            weiboDataCacheService.cacheFollowData(order.getUrl(), order.getSFollow());
        } else if (order.getGoods().getType() == 6) {
            weiboDataCacheService.cacheVideoData(order.getUrl(), order.getSVideo());
        } else if (order.getGoods().getType() == 10) {
            weiboDataCacheService.cacheCommentGoodData(order.getRefundNumber(), order.getSGood());
        } else if (order.getGoods().getType() != 5) {
            ArrayList<Integer> data = new ArrayList<>();
            data.add(order.getSForward());
            data.add(order.getSComment());
            data.add(order.getSGood());
            weiboDataCacheService.cacheBaseData(order.getUrl(), data);

        }
    }

    public static Bill setBillType(Bill bill,Goods goods){
        switch (goods.getType()){
            case 1:
                bill.setType(21);
                return bill;
            case 2:
                bill.setType(22);
                return bill;
            case 3:
                bill.setType(23);
                return bill;
            case 4:
                bill.setType(24);
                return bill;
            case 5:
                bill.setType(25);
                return bill;
            case 6:
                bill.setType(26);
                return bill;
            case 7:
                bill.setType(27);
                return bill;
            case 8:
                bill.setType(28);
                return bill;
            case 9:
                bill.setType(29);
                return bill;
            case 10:
                bill.setType(30);
                return bill;
        }
        return bill;
    }

//    @Override
//    public List<Order> loadByShopId(Long shopId) {
//        return orderMapper.loadByShopId(shopId);
//    }

    @Override
    public Boolean addorderByunified(UnifiedDto dto) {
        Goods goods = goodsMapper.loadById(dto.getSId());
        if(ObjectUtil.isEmpty(goods)){
            throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("下单失败！ " +"商品已下架请刷新页面"));
        }
        Order order = new Order();
        order.setSId(dto.getSId());
        order.setShopId(dto.getShopId());
        order.setUId(dto.getUId());
        Shop shop = shopMapper.loadById(order.getShopId());
        // 设置商家 id
        order.setShopId(shop.getBusinessId());
        order.setUrl(dto.getUrl());
        order.setOType(BaseConstants.Order.STATE_PENDORDER);
        //拿到uid  判断余额是否足够
        User user = userMapper.loadById(dto.getUId());
        String count = dto.getCount();
        String price = dto.getPrice();
        int countf = 0;
        int countc = 0;
        int countg = 0;
        BigDecimal pricef = null;
        BigDecimal pricec = null;
        BigDecimal priceg = null;

        BigDecimal finalypricef = null;
        BigDecimal finalypricec =null;
        BigDecimal finalypriceg =null;

        BigDecimal totalPrice = null;
        try {
            JSONObject jsonObject = JSONObject.parseObject(count);
            JSONObject priceall = JSONObject.parseObject(price);
            countf = jsonObject.getIntValue("countf");
            countc = jsonObject.getIntValue("countc");
            countg = jsonObject.getIntValue("countg");
            pricef = priceall.getBigDecimal("pricef");
            pricec = priceall.getBigDecimal("pricec");
            priceg = priceall.getBigDecimal("priceg");
            BigDecimal bigcountf = new BigDecimal(countf);
            BigDecimal bigcountc = new BigDecimal(countc);
            BigDecimal bigcountg = new BigDecimal(countg);
            finalypricef = pricef.multiply(bigcountf);
            finalypricec = pricec.multiply(bigcountc);
            finalypriceg = priceg.multiply(bigcountg);
            totalPrice = finalypricef.add(finalypricec).add(finalypriceg);
            if (ObjectUtils.isEmpty(user.getBalance()) || (user.getBalance().subtract(totalPrice).compareTo(BigDecimal.ZERO) < 0)|| user.getBalance().compareTo(BigDecimal.ZERO) <= 0) {
                throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("余额不足,当前余额:" + (user.getBalance() == null ? "0" : user.getBalance().toString()) + "  请充值"));
            }


            order.setGoods(goods);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置订单状态为创建
        order.setOType(BaseConstants.Order.STATE_PENDORDER);
        order.setGoods(goods);
        String url1 = order.getUrl();
        String url = url1.trim();
        String s = newToUrl(url);
        order.setUrl(s);
        if(order.getUrl().isEmpty() && order.getUrl().equals("")){
            throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("链接有误，请检查链接"));
        }
        
        // 以下不再进行微博数据爬取，采用默认值，后续异步更新
        // 为三个订单设置默认初始值
        Order orderf = setsome(order);
        Order orderc = setsome(order);
        Order orderg = setsome(order);
        
        // 设置订单的初始剩余量 完成量
        String f = UUID.randomUUID().toString();
        orderf.setCount(countf);
        orderf.setSurplus(countf);
        orderf.setOId(f);
        orderf.setFinalPrice(finalypricef);
        orderf.setSType(2);
        setDefaultInitialValues(orderf); // 使用默认初始值
        orderMapper.insert(orderf);

        orderc.setCount(countc);
        orderc.setSurplus(countc);
        String c = UUID.randomUUID().toString();
        orderc.setOId(c);
        orderc.setFinalPrice(finalypricec);
        orderc.setSType(3);
        setDefaultInitialValues(orderc); // 使用默认初始值
        orderMapper.insert(orderc);

        orderg.setCount(countg);
        orderg.setSurplus(countg);
        String g = UUID.randomUUID().toString();
        orderg.setOId(g);
        orderg.setFinalPrice(finalypriceg);
        orderg.setSType(4);
        setDefaultInitialValues(orderg); // 使用默认初始值
        orderMapper.insert(orderg);


        //扣除余额
        user.setBalance(user.getBalance().subtract(totalPrice));
        userMapper.update(user);

        //账单记录
        Bill bill = new Bill();
        bill.setMoney(totalPrice);
        bill.setType(28);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf1.format(new Date());
        bill.setTime(formattedDate);
        bill.setUserid(order.getUId());
        User user1 = userMapper.loadById(user.getId());
        bill.setBalance(user1.getBalance());
        billMapper.insert(bill);

        return true;
    }

    @Override
    @Transactional
    public AjaxResult refreshByFllow(Long ShopId) throws IOException, JSONException {
        List<Order> list = orderMapper.loadByShopId(ShopId, 1);
        if(list.size() == 0){
            return AjaxResult.me().setMessage("当前无关注数据");
        }
        List<Order> first200Orders = list.stream()
                .limit(1000) // 如果list长度大于200，则只取前200个
                .collect(Collectors.toList());
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i <=200; i++) {
            executor.submit(() -> {

                for (Order order : first200Orders) {
                    try {
                        if(order.getUrl() != null && order.getUrl() != ""){
                    //根据type不同使用不同的方法刷新 此方法为关注刷新
                        String fllow = Utils.getFllow();
                        String subValue = Utils.getSubValue(fllow);
                        FllowDto fllowDto = new FllowDto();
                        fllowDto.setSub(subValue);
                        fllowDto.setUrl(order.getUrl());
                        Integer followdata = Utils.getFollowdata(fllowDto);
                        Integer surplus1 = (order.getSFollow() + order.getCount()) - followdata;
                        Order order1 = countC(followdata-order.getSFollow(), order);
                        if(surplus1 > 0){
                            order.setSurplus(surplus1);
                        } else if(surplus1<=0) {
                            order.setSurplus(0);
                        }
                        if(surplus1>order.getCount()){
                            order.setSurplus(order.getCount());
                        }
                            orderMapper.update(order1);
                        }
                        System.out.println("成功刷新转发!" + order.getUrl());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    // 模拟任务执行耗时
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            executor.shutdown();
        }
//        for (Order order : list) {

//        }
        return AjaxResult.me().setMessage("关注数据刷新成功!");
    }



    @Override
//    @Transactional
    //@Async("task")
    public AjaxResult refreshByBase(Long shopId) {
        List<Order> list = orderMapper.loadByShopId(shopId, 2);
        List<Order> first200Orders = list.stream()
                .limit(1000) // 如果list长度大于200，则只取前200个
                .collect(Collectors.toList());
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i <=200; i++) {
            executor.submit(() -> {

                for (Order order : first200Orders) {
                    try {
                        AjaxResult refreshone = refreshone(order);
                        System.out.println("成功刷新转发!" + order.getUrl());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    // 模拟任务执行耗时
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            executor.shutdown();
        }
        return AjaxResult.me().setMessage("基础数据类型-转发-已刷新!");
    }

    @Override
    public AjaxResult refreshByBaseByc(Long shopId) {
        List<Order> list = orderMapper.loadByShopId(shopId, 3);
        List<Order> first200Orders = list.stream()
                .limit(600) // 如果list长度大于200，则只取前200个
                .collect(Collectors.toList());
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i <=200; i++) {
            executor.submit(() -> {

                for (Order order : first200Orders) {
                    try {
                        AjaxResult refreshone = refreshone(order);
                        System.out.println("成功刷新评论!" + order.getUrl());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    // 模拟任务执行耗时
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            executor.shutdown();
        }
        return AjaxResult.me().setMessage("基础数据类型-评论-已刷新!");
    }

    @Override
    public AjaxResult refreshByBaseByg(Long shopId) {
        List<Order> list = orderMapper.loadByShopId(shopId, 4);
        List<Order> first200Orders = list.stream()
                .limit(600) // 如果list长度大于200，则只取前200个
                .collect(Collectors.toList());
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i <=200; i++) {
            executor.submit(() -> {

                for (Order order : first200Orders) {
                    try {
                        AjaxResult refreshone = refreshone(order);
                        System.out.println("成功刷新点赞!" + order.getUrl());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    // 模拟任务执行耗时
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            executor.shutdown();
        }
        return AjaxResult.me().setMessage("基础数据类型-点赞-已刷新!");
    }

    @Override
    public AjaxResult refreshByBaseByp(Long shopId) {
        List<Order> list = orderMapper.loadByShopId(shopId, 7);
        List<Order> first200Orders = list.stream()
                .limit(600) // 如果list长度大于200，则只取前200个
                .collect(Collectors.toList());
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i <=200; i++) {
            executor.submit(() -> {
                for (Order order : first200Orders) {
                    try {
                        AjaxResult refreshone = refreshone(order);
                        System.out.println("成功刷新-真人转评赞!" + order.getUrl());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    // 模拟任务执行耗时
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            executor.shutdown();
        }
        return AjaxResult.me().setMessage("基础数据类型-真人转评赞-已刷新!");
    }

    @Override
    @Transactional
    public AjaxResult processing(Long shopId)  {
        //先拿到 type=7 的订单 待处理
        List<Order> list = orderMapper.loadByProcessing(shopId,7);
        if(list.size()==0){
            return AjaxResult.me().setMessage("无待处理订单---");
        }
        List<Order> first200Orders = list.stream()
                .limit(500) // 如果list长度大于200，则只取前200个
                .collect(Collectors.toList());
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i <=500; i++) {
            executor.submit(() -> {
                String url = null;
                for (Order order : first200Orders) {
                    if(order.getUrl().isEmpty() && order.getUrl().equals("")){
                        throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("链接有误，请检查链接"));
                    }
                    // 判断是否关注
                    if(order.getGoods().getType() == 1){
                        String fllow = null;
                        try {
                            fllow = Utils.getFllow();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        String subValue = Utils.getSubValue(fllow);
                        FllowDto fllowDto = new FllowDto();
                        fllowDto.setSub(subValue);
                        fllowDto.setUrl(order.getUrl());
                        Integer followdata = null;
                        try {
                            followdata = Utils.getFollowdata(fllowDto);
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        order.setSFollow(followdata);
                    }else if(order.getGoods().getType() == 6){
                        AjaxResult ajaxResult = VideoUtils.ToolUtils(order.getUrl());
                        if(!ajaxResult.getSuccess()){
                            order.setOType(6);
                            orderMapper.update(order);
                            continue;
                        }
                        String videoData =(String) ajaxResult.getResultObj();
                        if(videoData == null){
                            throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("链接有误，请检查链接"));
                        }
                        Integer sv = VideoUtils.convertToWan(videoData);
                        order.setSVideo(sv);
                    } else if(order.getGoods().getType() == 5){
                        order.setSFollow(1);
                    }else {
                        if(!order.getUrl().contains("m.weibo.cn")){
                            url = Utils.dealStr(order.getUrl());
                        }
                        if(Utils.ToolUtils(url).getSuccess()){
                            ArrayList<Integer> arrayList =( ArrayList<Integer>) Utils.ToolUtils(url).getResultObj();
                            order.setSForward(arrayList.get(0));
                            order.setSComment(arrayList.get(1));
                            order.setSGood(arrayList.get(2));
                            if(order.getGoods().getType() == 7){
                                //是否真人转评赞
                                order.setCompletionSf(0);
                                order.setCompletionSc(0);
                                order.setCompletionSg(0);
                                order.setSurplusSf(order.getCount());
                                order.setSurplusSc(order.getCount());
                                order.setSurplusSg(order.getCount());
                            }
                        } else {
                            order.setOType(6);
                            orderMapper.update(order);
                            continue;
                        }

                    }
                    //设置为待接单---
                    order.setOType(1);
                    orderMapper.update(order);
                }
                try {
                    // 模拟任务执行耗时
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            executor.shutdown();
        }
        return AjaxResult.me();
    }

    @Override
    public List<Order> receivingByshopId(ReceivingDto receivingDto) {
        List<Order> list = orderMapper.loadByProcessing(receivingDto.getShopId(), receivingDto.getGtype());
        List<Order> backdata = new ArrayList<>();
        // 爬取微博初始化数据
        for (Order order1 : list) {
            Order order = orderMapper.loadById(order1.getId());
            order.setOType(BaseConstants.Order.STATE_ONGOING);
            orderMapper.update(order);
            backdata.add(order);
        }
        return backdata;
    }

    @Override
    public AjaxResult refreshByConmentGoos(Long shopId) {
        List<Order> list = orderMapper.loadByShopId(shopId, 10);
        List<Order> first200Orders = list.stream()
                .limit(600) // 如果list长度大于200，则只取前200个
                .collect(Collectors.toList());
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i <=200; i++) {
            executor.submit(() -> {

                for (Order order : first200Orders) {
                    try {
                        AjaxResult ajaxResult = ConmentUtils.GetComment(order.getRefundNumber());
                        if(ajaxResult.getSuccess()){
                            String s = (String) ajaxResult.getResultObj();
                            if(s!=null){
                                Integer sg = VideoUtils.convertToWan(s);
                                int  result = order.getSGood()+order.getCount()-sg;
                                if(result>0){
                                    order.setCompletion(sg-order.getSGood());
                                    order.setSurplus(result);
                                }
                                if(result<=0){
                                    order.setCompletion(order.getCount());
                                    order.setSurplus(0);
                                    order.setOType(3);
                                }
                                orderMapper.update(order);
                            }
                        }

                        System.out.println("成功刷新内评赞!" + order.getUrl());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    // 模拟任务执行耗时
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            executor.shutdown();
        }
        return AjaxResult.me().setMessage("基础数据类型-内评赞-已刷新!");
    }

    @Override
    public AjaxResult refreshByBaseByt(Long shopId) {
        List<Order> list = orderMapper.loadByShopId(shopId, 8);
        List<Order> first200Orders = list.stream()
                .limit(600) // 如果list长度大于200，则只取前200个
                .collect(Collectors.toList());
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i <=200; i++) {
            executor.submit(() -> {
                for (Order order : first200Orders) {
                    try {
                        AjaxResult refreshone = refreshone(order);
                        System.out.println("成功刷新-统一转评赞!" + order.getUrl());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    // 模拟任务执行耗时
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            executor.shutdown();
        }
        return AjaxResult.me().setMessage("基础数据类型-统一转评赞-已刷新!");
    }

    @Override
    public AjaxResult refreshByBaseBycmc(Long shopId) {
        List<Order> list = orderMapper.loadByShopId(shopId, 9);
        List<Order> first200Orders = list.stream()
                .limit(600) // 如果list长度大于200，则只取前200个
                .collect(Collectors.toList());
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i <=200; i++) {
            executor.submit(() -> {

                for (Order order : first200Orders) {
                    try {
                        AjaxResult refreshone = refreshone(order);
                        System.out.println("成功刷新评中评!" + order.getUrl());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    // 模拟任务执行耗时
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            executor.shutdown();
        }
        return AjaxResult.me().setMessage("基础数据类型-评中评-已刷新!");
    }

    @Override
    public AjaxResult refreshByBaseByTall(Long shopId) {
        List<Order> list = orderMapper.loadByShopId(shopId, 8);
        List<Order> first200Orders = list.stream()
                .limit(600) // 如果list长度大于200，则只取前200个
                .collect(Collectors.toList());
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i <=200; i++) {
            executor.submit(() -> {

                for (Order order : first200Orders) {
                    try {
                        AjaxResult refreshone = refreshone(order);
                        System.out.println("成功刷新统一转评赞!" + order.getUrl());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    // 模拟任务执行耗时
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            executor.shutdown();
        }
        return AjaxResult.me().setMessage("基础数据类型-统一转评赞-已刷新!");
    }

    @Override
    public UserOrderStatusCounts countOderByUser(Long uid) {
        return orderMapper.countOderByUser(uid);
    }


    public AjaxResult refreshone(Order order){
        String url = order.getUrl().trim();
        AjaxResult ajaxResult = Utils.ToolUtils(url);
        if (!ajaxResult.getSuccess()) {
            order.setOType(6); //异常
            orderMapper.update(order);
            return AjaxResult.me();
        }
        ArrayList<Integer> data = (ArrayList<Integer>) ajaxResult.getResultObj();
        if (order.getGoods().getType() == 2) {
            Integer sf = data.get(0);
            Order order2 = countC(sf - order.getSForward(), order);
            int surplus2 = (order.getSForward() + order.getCount()) - sf;

            if (surplus2 > 0) {
                order2.setSurplus(surplus2);
            } else {
                order2.setSurplus(0);
            }
            System.out.println("更新操作-转发");
            orderMapper.update(order2);
        }
        if (order.getGoods().getType() == 3) {
            Integer sc = data.get(1);
            Order order2 = countC(sc - order.getSComment(), order);
            int surplus2 = (order.getSComment() + order.getCount()) - sc;

            if (surplus2 > 0) {
                order2.setSurplus(surplus2);
            } else {
                order2.setSurplus(0);
            }
            System.out.println("更新操作-评论");
            orderMapper.update(order2);
        }
        if (order.getGoods().getType() == 4) {
            Integer sg = data.get(2);
            Order order2 = countC(sg - order.getSGood(), order);
            int surplus2 = (order.getSGood() + order.getCount()) - sg;

            if (surplus2 > 0) {
                order2.setSurplus(surplus2);
            } else {
                order2.setSurplus(0);
            }
            System.out.println("更新操作-点赞");
            orderMapper.update(order2);
        }
        if(order.getGoods().getType() == 7){
            Order order4= countTypeSeven(data, order);
                    // 设置剩余量
            if(order.getOType() == 2){
                order4.setSurplusSf((order.getSForward() + order.getCount()) - data.get(0));
                order4.setSurplusSc((order.getSComment() + order.getCount()) - data.get(1));
                order4.setSurplusSg((order.getSGood() + order.getCount()) - data.get(2));
            }else if(order.getOType() == 4){
                order4.setSurplus(0);
                order4.setSurplusSf(0);
                order4.setSurplusSc(0);
                order4.setSurplusSg(0);
            }
            orderMapper.update(order4);
        }
        if(order.getGoods().getType()==8){
            if(order.getSType() == 2){
                Integer sf = data.get(0);
                Order order2 = countC(sf - order.getSForward(), order);
                int surplus2 = (order.getSForward() + order.getCount()) - sf;

                if (surplus2 > 0) {
                    order2.setSurplus(surplus2);
                } else {
                    order2.setSurplus(0);
                }
                System.out.println("更新操作-统一转发");
                orderMapper.update(order2);
            }
            if(order.getSType() == 3){
                Integer sc = data.get(1);
                Order order2 = countC(sc - order.getSComment(), order);
                int surplus2 = (order.getSComment() + order.getCount()) - sc;

                if (surplus2 > 0) {
                    order2.setSurplus(surplus2);
                } else {
                    order2.setSurplus(0);
                }
                System.out.println("更新操作-统一评论");
                orderMapper.update(order2);
            }
            if(order.getSType() == 4){
                Integer sg = data.get(2);
                Order order2 = countC(sg - order.getSGood(), order);
                int surplus2 = (order.getSGood() + order.getCount()) - sg;

                if (surplus2 > 0) {
                    order2.setSurplus(surplus2);
                } else {
                    order2.setSurplus(0);
                }
                System.out.println("更新操作-统一点赞");
                orderMapper.update(order2);
            }
        }
        if(order.getGoods().getType()==9){
            Integer sc = data.get(1);
            Order order2 = countC(sc - order.getSComment(), order);
            int surplus2 = (order.getSComment() + order.getCount()) - sc;

            if (surplus2 > 0) {
                order2.setSurplus(surplus2);
            } else {
                order2.setSurplus(0);
            }
            System.out.println("更新操作-评中评");
            orderMapper.update(order2);
        }
        return AjaxResult.me();
    }

    @Override
    public AjaxResult refreshByVideo(Long shopId){
        List<Order> list = orderMapper.loadByShopId(shopId, 6);
        if(list.size()==0){
            return AjaxResult.me().setMessage("无播放订单");
        }
        List<Order> first200Orders = list.stream()
                .limit(600) // 如果list长度大于200，则只取前200个
                .collect(Collectors.toList());
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i <=200; i++) {
            executor.submit(() -> {
                for (Order order : first200Orders) {
                    try {
                        AjaxResult ajaxResult = VideoUtils.ToolUtils(order.getUrl());
                        if(!ajaxResult.getSuccess()){
                            order.setOType(6);
                            orderMapper.update(order);
                        }
                        String videoData = (String) ajaxResult.getResultObj();
                        Integer sv = VideoUtils.convertToWan(videoData);
                        Order order6 = countC(sv-order.getSVideo(), order);
                        // 设置剩余量
                        int surplus6 = (order.getSVideo() + order.getCount()) - sv;

                        if (surplus6 <= 1000) {
                            order6.setSurplus(0);
                            order6.setCompletion(order.getCount());
                            order6.setOType(BaseConstants.Order.STATE_FINISHED);
                        } else if(surplus6 > 1000) {
                            order6.setSurplus(surplus6);
                        }
                        if(surplus6>=order.getCount()){
                            order6.setSurplus(order.getCount());
                        }
                        if(order.getSVideo() == order.getSurplus()){
                            order6.setSurplus(0);
                            order6.setCompletion(order.getCount());
                            order6.setOType(3);
                        }
                        orderMapper.update(order6);
                        System.out.println("成功刷新视频播放!" + order.getUrl());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    // 模拟任务执行耗时
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            executor.shutdown();
        }
        return AjaxResult.me().setMessage("视频播放-已刷新!");
    }



    public Order countC(Integer relut, Order order) {
        if (relut >= order.getCount()) {
            order.setCompletion(order.getCount());
            order.setOType(BaseConstants.Order.STATE_FINISHED);
        } else if (relut > 0 && relut < order.getCount()) {
            order.setCompletion(relut);
            order.setOType(BaseConstants.Order.STATE_ONGOING);
        } else if (relut <= 0) {
            order.setCompletion(0);
        }
        return order;
    }

    public Order countTypeSeven(ArrayList<Integer> arrayList,Order order){
        int resultf = arrayList.get(0) - order.getSForward();
        int resultc = arrayList.get(1) - order.getSComment();
        int resultg = arrayList.get(2) - order.getSGood();
        if(resultf>= order.getCount() && resultc>=order.getCount() && resultg>=order.getCount() ){
            order.setCompletion(order.getCount());
            order.setOType(BaseConstants.Order.STATE_FINISHED);
        }else {
            order.setCompletionSf(arrayList.get(0)-order.getSForward());
            order.setCompletionSc(arrayList.get(1)-order.getSComment());
            order.setCompletionSg(arrayList.get(2)-order.getSGood());
            order.setOType(BaseConstants.Order.STATE_ONGOING);
        }
        return order;
    }

    /**
     * 商家接单
     *
     * @param id
     */

    @Override
    public void receivingById(Long id) {
        orderMapper.updateType(id, BaseConstants.Order.STATE_ONGOING);
    }

    /**
     * 批量接单
     *
     * @param ids
     */
    @Override
    public void receivingByIds(List<Long> ids) {
        //判断是否为空
        if (ids == null || ids.size() == 0) {
            throw new RuntimeException("没有选中数据，接单失败");
        }

        List<Order> orders = orderMapper.loadByIdOrType(ids, BaseConstants.Order.STATE_PENDORDER);
        //判断这些订单是否为待接单
        if (orders == null || orders.size() == 0) {
            throw new RuntimeException("请选择待接单的订单!");
        }

        List<Long> listIds = orders.stream().map(x -> x.getId()).collect(Collectors.toList());
        // 爬取微博初始化数据
        for (Long id : listIds) {
            Order order = orderMapper.loadById(id);
            order.setOType(BaseConstants.Order.STATE_ONGOING);
            orderMapper.update(order);
        }

    }

//    @Override
//    public List<Order> loadByUid(Long id) {
//        List<Order> list =orderMapper.loadByUid(id);
//        return list;
//    }

    @Override
    public Order loadByOid(String oid) {
        Order order = orderMapper.loadByOid(oid);
        return order;
    }


    /**
     * 后台商家退款
     *
     * @param refundDto
     */
    @Override
    @Transactional
    public AjaxResult merchantRefund(RefundDto refundDto) {
        Order order = orderMapper.loadByOid(refundDto.getOid());
        // 算出应该给客户退款的余额，并退给用户
        User user = userMapper.loadById(order.getUId());
        int num = Integer.parseInt(refundDto.getNum());
        if(num>order.getCount()){
           return AjaxResult.me().setSuccess(false).setMessage("退款数量大于订单量，请重新输入!");
        }
        // 商品单价
        BigDecimal goodsPrice = order.getFinalPrice().divide(BigDecimal.valueOf(order.getCount()));
        user.setBalance(user.getBalance().add(goodsPrice.multiply(BigDecimal.valueOf(order.getCount()-num))));
        userMapper.update(user);
        //账单记录
        Bill bill = new Bill();
        bill.setMoney(goodsPrice.multiply(BigDecimal.valueOf(order.getCount()-num)));
        bill.setType(3);
        bill.setBtype(3);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(date);
        bill.setTime(formattedDate);
        bill.setUserid(order.getUId());
        User user1 = userMapper.loadById(order.getUId());
        bill.setBalance(user1.getBalance());
        billMapper.insert(bill);
        // 修改订单状态
        order.setOType(BaseConstants.Order.STATE_CNACLEOEDER);
        orderMapper.update(order);
        return AjaxResult.me();
    }

    /**
     * 批量退款
     * @param orderList
     */
    @Override
    public AjaxResult bulkRefund(List<Order> orderList) {
        for (Order order : orderList) {
            // 算出应该给客户退款的余额，并退给用户
            User user = userMapper.loadById(order.getUId());
            int num = Integer.parseInt(order.getRefundNumber());
            if(num>order.getCount()){
                return AjaxResult.me().setSuccess(false).setMessage("订单 id 为：" + order.getId() + "的订单输入的退款数量大于订单量，请重新输入!");
            }
            // 商品单价
            BigDecimal goodsPrice = order.getFinalPrice().divide(BigDecimal.valueOf(order.getCount()));
            user.setBalance(user.getBalance().add(goodsPrice.multiply(BigDecimal.valueOf(order.getCount()-num))));
            userMapper.update(user);
            //账单记录
            Bill bill = new Bill();
            bill.setMoney(goodsPrice.multiply(BigDecimal.valueOf(order.getCount()-num)));
            bill.setType(3);
            bill.setBtype(3);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(date);
            bill.setTime(formattedDate);
            bill.setUserid(order.getUId());
            User user1 = userMapper.loadById(order.getUId());
            bill.setBalance(user1.getBalance());
            billMapper.insert(bill);

            // 修改订单状态
            order.setOType(BaseConstants.Order.STATE_CNACLEOEDER);
            orderMapper.update(order);
            AjaxResult.me().setMessage("批量退款成功");
        }
        return AjaxResult.me();
    }

    @Override
    public void completeByOrder(Long id) {
        Order order = orderMapper.loadById(id);
        order.setCompletion(order.getCount());
        order.setOType(BaseConstants.Order.STATE_FINISHED);
        order.setSurplus(0);
        orderMapper.update(order);
    }



    /**
     * 获取退款订单
     * @param ids
     * @return
     */
    @Override
    public List<Order> loadRefundOrderByIds(List<Long> ids) {


        return orderMapper.loadRefundOrderByIds(ids);
    }

    @Override
    public List<Copy> SelectByIds(List<Long> ids) {
        List<Copy> copies = new ArrayList<>();
        List<Order> orders = orderMapper.selectByIds(ids);
        for (Order order : orders) {
            Copy copy = new Copy();
            copy.setUrl(order.getUrl());
            copy.setCount(order.getCount());
            copy.setCount(order.getSurplus());
            Goods goods = goodsMapper.loadById(order.getSId());
            copy.setType(goods.getType());
            String s = new String();
            if(goods.getType() == 7){
                copy.setSurplusSf(order.getSurplusSf());
                copy.setSurplusSc(order.getSurplusSc());
                copy.setSurplusSg(order.getSurplusSg());
            }
            s=Typesurplus(goods.getType(),order);
            copy.setStr(s);
            copies.add(copy);
        }
        copies.sort(Comparator.comparing(Copy::getType));

        return copies;
    }

    private String Typesurplus(Integer type, Order order) {
        switch (type){
            case 1:
                return order.getUrl()+" "+"关注"+" "+order.getSurplus();
            case 2:
                return order.getUrl()+" "+"转发"+" "+order.getSurplus();
            case 3:
                return order.getUrl()+" "+"评论"+" "+order.getSurplus();
            case 4:
                return order.getUrl()+" "+"点赞"+" "+order.getSurplus();
            case 5:
                return order.getUrl()+" "+"阅读"+" "+order.getSurplus();
            case 6:
                return order.getUrl()+" "+"视频播放"+" "+order.getSurplus();
            case 7:
                return order.getUrl()+" "+"真人转评赞"+" "+order.getSurplusSf()+"  "+order.getSurplusSc()+" "+order.getSurplusSg();
            case 8:
                if(order.getSType() ==2 ){
                    return order.getUrl()+" "+"转发"+" "+order.getSurplus();
                }
                if(order.getSType() ==3){
                    return order.getUrl()+" "+"评论"+" "+order.getSurplus();
                }
                if(order.getSType() ==4){
                    return order.getUrl()+" "+"点赞"+" "+order.getSurplus();
                }
            case 9:
                return order.getUrl()+" "+order.getRefundNumber()+" "+"评中评"+" "+order.getSurplus();
            case 10:
                return order.getRefundNumber()+" "+"内评赞"+"  "+order.getSurplus();

        }
       return null;
    }

    @Override
    public Copy SelectById(Long id) {
        Order order = orderMapper.loadById(id);
        Goods goods = goodsMapper.loadById(order.getSId());
        order.setGoods(goods);
        Copy copy = new Copy();
//        if(!order.getUrl().contains("m.weibo.cn")){
//            copy.setUrl(Utils.dealStr(order.getUrl()));
//        }else {
//            copy.setUrl(order.getUrl());
//        }
        if(order.getGoods().getType()!=10){
            String su = newToUrl(order.getUrl());
            copy.setUrl(su);
        }


        copy.setCount(order.getSurplus());
        copy.setSurplusSf(order.getSurplusSf());
        copy.setSurplusSc(order.getSurplusSc());
        copy.setSurplusSg(order.getSurplusSg());

//        copy.setName(goods.getName());
        copy.setType(goods.getType());
        String s = "";
        s=Typesurplus(goods.getType(),order);
        copy.setStr(s);
        return copy;
    }



    @Override
//    @Transactional
    public Boolean addLotOrder(List<Order> orders) throws JSONException, IOException {
        int count = 0;
        //拿到uid  判断余额是否足够
        User user = userMapper.loadById(orders.get(0).getUId());
        for (Order order: orders){
            if(order.getCount()!=0 && order.getCount()!=null){
                count = order.getCount()+count;
            }
        }
        Goods goods1 = goodsMapper.loadById(orders.get(0).getSId());
        if (orders == null || orders.isEmpty()) {
            return false;
        }
        if(count == 0){
            throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("订单数量为0,请正确下单"));
        }
        //计算总额
        BigDecimal finalPrice = goods1.getPrice().multiply(new BigDecimal(count));
        if (ObjectUtils.isEmpty(user.getBalance()) || (user.getBalance().subtract(finalPrice).compareTo(BigDecimal.ZERO) < 0)) {
            throw new UserBaseException(AjaxResult.me().setSuccess(false).setMessage("余额不足,请充值"));
        }
        
        for (Order order : orders) {
            try {
                // 设置默认初始值，异步更新将在Controller中处理
                setDefaultInitialValues(order);
                this.addOrder(order);
            } catch (Exception e) {
                // 记录错误但继续处理下一个订单
                e.printStackTrace();
            }
        }
        return true;
    }

    @Override
    public AjaxResult newOrder(NewOrderDto dto) {


        long l = orderMapper.loadnewTotal(dto.getShopId());
        if(l==0){
            return AjaxResult.me().setSuccess(false).setMessage("当前无订单");
        }
        if(dto.getTotal()==null || dto.getTotal()==l){
            return AjaxResult.me().setSuccess(false).setMessage("当前无新订单!").setResultObj(l);
        }
        if(dto.getTotal()<l){
            return AjaxResult.me().setMessage("有新订单啦!,请尽快接单!").setResultObj(l);
        }
        return AjaxResult.me().setSuccess(false).setMessage("数据库存在脏数据，请联系开发人员!");
    }

    @Override
    public AjaxResult getTotal(Long shopid) {
        long l = orderMapper.loadnewTotal(shopid);
        return AjaxResult.me().setResultObj(l);
    }

    @Override
    public PageList<Order> pageList(OrderQuery query)  {
        //查询总条数
//        System.out.println(query.getCreateTime());
        long total = orderMapper.loadTotal(query);
        if (total > 0){
            List<Order> rows = orderMapper.pageList(query);
            return new PageList<Order>(total, rows);
        }
        return new PageList<>();
    }

    @Override
    public void deleteBytime(DeleteDto dto) {
        orderMapper.deleteBytime(dto);
    }


    public static String newToUrl(String s){
        int wen = s.indexOf("?");
        int jin = s.indexOf("#");
        if (wen != -1) { // 如果找到了?
            String modifiedUrl = s.substring(0, wen); // 截取?之前的部分
            System.out.println(modifiedUrl); // 输出结果
            return modifiedUrl;
        }
        if(jin !=-1){
            String modifiedUrl = s.substring(0, jin); // 截取?之前的部分
            System.out.println(modifiedUrl);
            return modifiedUrl;
        }
        return s;
    }

    public static Order setsome(Order order){
        return order;
    }

}
